/****************************************************************************
*                                                                           *
* Copyright (c) RSC. All rights reserved(2010).								*
* Developers: Marius Ionescu, Cristian Bojinovici     						*
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.Security;
using System.Web.UI.WebControls;
using NS_Controls;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.UI;
using AjaxControlToolkit;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

public partial class ReportsLaboratory : SessionPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                SetInitialFilters();
                LoadDataBI();
                LoadDataSR();
            }
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
            filterOutput.Text += "<!-- " + ex.ToString() + " -->";
        }
    }

    private void SetInitialFilters()
    {
        txtStartDate.Text = DateTime.Now.ToString(extStartDate.Format);
        txtStartTime.Text = "00:00";
        txtEndDate.Text = txtStartDate.Text;
        txtEndTime.Text = "23:59";

        //load lists from db:
        #region sectii
        {
            string sqlSection = "select distinct s.* from SECTIONS s ";
            sqlSection += " order by s.Name";
            DataTable dtShowSections = ReportsLaboratory.GetDbData(sqlSection, "code", "Name");
            DataRow firstSection = dtShowSections.NewRow(); firstSection["code"] = ""; firstSection["Name"] = "Toate sectiile";
            dtShowSections.Rows.InsertAt(firstSection, 0);
            DataRow secondSection = dtShowSections.NewRow(); secondSection["code"] = "grouped"; secondSection["Name"] = "Grupat pe sectie";
            dtShowSections.Rows.InsertAt(secondSection, 1);
            strSection.DataSource = dtShowSections;
            strSection.DataValueField = "code";
            strSection.DataTextField = "Name";
            strSection.DataBind();
        }
        #endregion
        #region sectii #2
        {
            string sqlSectionParaclinic = @"select * from Sections where Paraclinic=1"; //NB: no sort?
            DataTable dtShowSection = ReportsLaboratory.GetDbData(sqlSectionParaclinic, "CODE", "Name");
            DataRow allSections = dtShowSection.NewRow(); allSections["CODE"] = 0; allSections["Name"] = "Oricare";
            dtShowSection.Rows.InsertAt(allSections, 0);
            strSection2.DataSource = dtShowSection;
            strSection2.DataValueField = "CODE";
            strSection2.DataTextField = "Name";
            strSection2.DataBind();
        }
        #endregion
        #region doctori
        {
            string sqlMedic = @"select distinct convert(varchar(42),ID) as ID, FullName from vMedics
				order by [FullName]"; //NB: the "vUsersAsMedics" isn't available.
            DataTable dtShowMedics = ReportsLaboratory.GetDbData(sqlMedic, "ID", "FullName");
            DataRow firstMedic = dtShowMedics.NewRow(); firstMedic["ID"] = ""; firstMedic["FullName"] = "Toti medicii";
            dtShowMedics.Rows.InsertAt(firstMedic, 0);
            DataRow secondMedic = dtShowMedics.NewRow(); secondMedic["ID"] = "grouped"; secondMedic["FullName"] = "Grupat pe medic";
            dtShowMedics.Rows.InsertAt(secondMedic, 1);
            strMedic.DataSource = dtShowMedics;
            strMedic.DataValueField = "ID";
            strMedic.DataTextField = "FullName";
            strMedic.DataBind();
            //strMedic.Items.Insert(0, new ListItem("txt", "val"));
        }
        #endregion
        #region tipuri de doctori
        {
            string sqlMedicType = @"select * from MEDIC_TYPES"; //NB: no sort?
            DataTable dtShowMedicTypes = ReportsLaboratory.GetDbData(sqlMedicType, "ID", "Type");
            DataRow allMedicTypes = dtShowMedicTypes.NewRow(); allMedicTypes["ID"] = 0; allMedicTypes["Type"] = "Oricare";
            dtShowMedicTypes.Rows.InsertAt(allMedicTypes, 0);
            strMedicType.DataSource = dtShowMedicTypes;
            strMedicType.DataValueField = "ID";
            strMedicType.DataTextField = "Type";
            strMedicType.DataBind();
        }
        #endregion
        #region tipuri de plati (x2)
        try
        {
            string sqlPayType = @"select distinct ID, Name, Active from PAYMENT_TYPES where Active = 1
				order by Active DESC, Name";
            DataSet dsPayTypes = Hipocrate.DB.DBConnection.GetData(sqlPayType);
            if (dsPayTypes != null)
            {
                dsPayTypes.Tables[0].Columns["Name"].ReadOnly = false;
                foreach (DataRow r in dsPayTypes.Tables[0].Rows)
                    if (!(bool)(r["Active"]))
                        r["Name"] += " (inactiv)";
                foreach (DropDownList ddl in new DropDownList[] { strPayType, strPayType2 })
                {
                    ddl.DataSource = dsPayTypes.Tables[0];
                    ddl.DataValueField = "ID";
                    ddl.DataTextField = "Name";
                    ddl.DataBind();
                }

                foreach (ListControl list in new object[] { filterTypePayment })
                {
                    list.DataSource = dsPayTypes.Tables[0];
                    list.DataValueField = "ID";
                    list.DataTextField = "Name";
                    list.DataBind();
                }

                foreach (ListItem chk in filterTypePayment.Items)
                {
                    chk.Selected = true;
                }
            }
        }
        catch (System.Data.SqlClient.SqlException) { }
        #endregion
        #region tipuri de analize
        {
            string sqlAnalyseTypes = "Select convert(varchar(42),ID) as ID, [Name] from Analyse_Types";
            DataTable dtAnalyseTypes = ReportsLaboratory.GetDbData(sqlAnalyseTypes, "ID", "Name");
            DataRow selectAllAnalyseTypes = dtAnalyseTypes.NewRow(); selectAllAnalyseTypes["ID"] = "all"; //selectAllAnalyseTypes["Name"] = "";
            dtAnalyseTypes.Rows.InsertAt(selectAllAnalyseTypes, 0);
            strAnalysis.DataSource = dtAnalyseTypes;
            strAnalysis.DataValueField = "ID";
            strAnalysis.DataTextField = "Name";
            strAnalysis.DataBind();
        }
        #endregion
        #region domenii ("tipuri") -- selection lists
        try
        {
            string sqlDomains = "select distinct '' as counter, [Domain] from LAB_DOMAINS ";
            //if not checkSecLevel(SEC_REPORTS) AND not checkSecLevel(SEC_ADMIN) then
            //    sqlDomains += "where Section='" + Session["Section"].ToString().Replace("'", "''") + "' ";
            sqlDomains += "order by [Domain]";
            DataSet dsDomains = Hipocrate.DB.DBConnection.GetData(sqlDomains);

            //DataRow selectAllAnalyseTypes = dsDomains.Tables[0].NewRow();
            //selectAllAnalyseTypes["Domain"] = "Toate";
            //dsDomains.Tables[0].Rows.InsertAt(selectAllAnalyseTypes, 0);

            if (dsDomains != null)
            {
                foreach (DataColumn c in dsDomains.Tables[0].Columns)
                    c.ReadOnly = false;
                int rowIndex = 0;
                foreach (DataRow r in dsDomains.Tables[0].Rows)
                {
                    r["counter"] = "class" + (++rowIndex).ToString();
                    r["Domain"] = r["Domain"].ToString().Replace(" ", "&nbsp;") + " "; //allow breaks only between items
                }
                foreach (ListControl list in new object[] { filterType, filterTypes })
                //both extend ListControl and also implement: IRepeatInfoUser, INamingContainer, IPostBackDataHandler
                {
                    list.DataSource = dsDomains.Tables[0];
                    list.DataValueField = "counter";
                    list.DataTextField = "Domain";
                    list.DataBind();
                    list.SelectedIndex = 0;
                }
            }
        }
        catch (System.Data.SqlClient.SqlException) { }
        #endregion
        #region recomandari/sectii -- chkbox list
        try
        {
            string sqlSectiiRecomandari = "select Code, [Name] from Sections where Ambulatory=1 or Guard=1 or Therapy=1 or Clinic=1 ";
            DataSet dsSectiiRecomandari = Hipocrate.DB.DBConnection.GetData(sqlSectiiRecomandari);
            if (dsSectiiRecomandari != null)
            {
                dsSectiiRecomandari.Tables[0].Columns["Name"].ReadOnly = false;
                foreach (DataRow r in dsSectiiRecomandari.Tables[0].Rows)
                    r["Name"] = r["Name"].ToString().Replace(" ", "&nbsp;") + " "; //allow breaks only between items
                filterSection.DataSource = dsSectiiRecomandari.Tables[0];
                filterSection.DataValueField = "Code";
                filterSection.DataTextField = "Name";
                filterSection.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException) { }
        #endregion

        checkAllSections.Text = "Toate";
        checkAllTypes.Text = "Toate";
        customSections.Text = "(selectate)";
        customTypes.Text = "(selectate)";
        checkNoSections.Text = "Niciuna";
        checkNoTypes.Text = "Niciunul";
        filterSection_SelectedIndexChanged(null, null);
        filterTypes_SelectedIndexChanged(null, null);

        ddlGrupRaport.SelectedIndex = 0;
        ddlGrupRaport_SelectedIndexChanged(null, null); //should also set visibilities and other such details
    }
    private static DataTable GetDbData(string sql, params string[] columnNames)
    {
        DataTable result = null;
        try
        {
            DataSet ds = Hipocrate.DB.DBConnection.GetData(sql);
            if (ds != null)
            {
                result = ds.Tables[0];
                foreach (DataColumn c in result.Columns)
                    c.AllowDBNull = true;
            }
        }
        catch (System.Data.SqlClient.SqlException) { }
        finally
        {
            if ((result == null) || (result.Columns.Count == 0))
            {
                result = new DataTable();
                foreach (string name in columnNames)
                    result.Columns.Add(name);
            }
        }
        return result;
    }

    private void LoadDataBI()
    {
        try
        {
            DataSet ds_Section = Hipocrate.DB.DBConnection.GetData("select distinct s.* from SECTIONS s");
            DataView dv0 = ds_Section.Tables[0].DefaultView;

            drpSectionIB.DataSource = dv0;
            drpSectionIB.DataTextField = "name";
            drpSectionIB.DataValueField = "code";
            drpSectionIB.DataBind();
            drpSectionIB.Items.Insert(0, "");

            DataSet ds_Medic = Hipocrate.DB.DBConnection.GetData("select distinct ID, FullName from vUsersAsMedics order by FullName");
            DataView dv1 = ds_Medic.Tables[0].DefaultView;

            drpMedicIB.DataSource = dv1;
            drpMedicIB.DataTextField = "FullName";
            drpMedicIB.DataValueField = "id";
            drpMedicIB.DataBind();
            drpMedicIB.Items.Insert(0, "");

            DataSet ds_Domain = Hipocrate.DB.DBConnection.GetData("select distinct [id],[Domain] from LAB_DOMAINS ");
            DataView dv2 = ds_Domain.Tables[0].DefaultView;

            drpTypesInv.DataSource = dv2;
            drpTypesInv.DataTextField = "Domain";
            drpTypesInv.DataValueField = "id";
            drpTypesInv.DataBind();
            drpTypesInv.Items.Insert(0, "");

            txtTimeStartIB.Text = "00:00";
            txtTimeEndIB.Text = "23:59";
            txtDataStart.Text = System.DateTime.Now.ToShortDateString();
            txtDataEnd.Text = System.DateTime.Now.ToShortDateString();
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    private void LoadDataSR()
    {
        try
        {
            DataSet ds_Domain = Hipocrate.DB.DBConnection.GetData("select distinct [id],[Domain] from LAB_DOMAINS order by [Domain]");
            DataView dv2 = ds_Domain.Tables[0].DefaultView;

            drpInvestigSR.DataSource = dv2;
            drpInvestigSR.DataTextField = "Domain";
            drpInvestigSR.DataValueField = "id";
            drpInvestigSR.DataBind();

            txtTimeDSSR.Text = "00:00";
            txtTimeEDSR.Text = "23:59";
            txtStartDataSR.Text = System.DateTime.Now.ToShortDateString();
            txtEndDataSR.Text = System.DateTime.Now.ToShortDateString();

            rdFormatSR.SelectedIndex = 0;
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    protected void ddlGrupRaport_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedPrefix = ddlGrupRaport.SelectedValue;
        bool foundFirst = false;
        int currentIndex = 0;
        foreach (ListItem item in ddlRaportSelector.Items)
        {
            item.Enabled = item.Value.StartsWith(selectedPrefix);
            if (item.Enabled && !foundFirst)
            {
                foundFirst = true;
                ddlRaportSelector.SelectedValue = item.Value; //"item.Selected = true;" wouldn't be enough
                ddlRaportSelector.SelectedIndex = currentIndex;
                ddlRaportSelector_SelectedIndexChanged(null, null); //changes the layout (visibilities) to fit the selection
            }
            ++currentIndex;
        }
        if (!foundFirst)
        {
            ddlRaportSelector.SelectedValue = null;
            ddlRaportSelector_SelectedIndexChanged(null, null); //changes the layout (visibilities) to fit the selection
        }
    }

    protected void ddlRaportSelector_SelectedIndexChanged(object sender, EventArgs e)
    {
        //selectedReportOutput.Text += "<br/>selected " + ddlRaportSelector.SelectedValue;
        #region update visibilities
        filtering.Visible = (ddlRaportSelector.SelectedIndex >= 0)
            || (sender == null); //also show when the ddlRaportSelector is empty, after manually trigerring this!
        if (filtering.Visible)
        {
            string reportType = ddlRaportSelector.SelectedValue;
            if (string.IsNullOrEmpty(reportType))
                reportType = ddlGrupRaport.SelectedValue;
            #region most common states
            trTimeInterval.Visible = true;
            {
                txtStartTime.Enabled = true;
                //txtStartTime.ReadOnly = false;
                txtEndTime.Enabled = true;
                //txtEndTime.ReadOnly = false;
            }
            trAnalysis.Visible = false;
            trSectionMedic.Visible = false;
            trPlati.Visible = true;
            {
                labelSpecifiedPayType.Visible = true;
                bSpecifiedPayType.Visible = true;
            }
            trSumming.Visible = false;
            trSectionMedic2.Visible = false;
            trDetails.Visible = true;
            {
                detailsLabel1.Visible = true;  //Processed
                detailsLabel2.Visible = false; //ShowFullInfo
            }
            trInvestigationResults.Visible = false;
            trResultValues.Visible = false;
            trExtra1.Visible = false;
            trExtra2.Visible = false;
            trExclusions.Visible = false;
            trOutputFormat1.Visible = true;
            {
                labelInternalNames.Visible = false;
                bInternalName.Visible = false;
            }
            trOutputFormat2.Visible = true;
            {
                labelInternalCodes.Visible = false;
                bInternalCode.Visible = false;
            }
            trGroupBySection.Visible = false;
            labelGroupBySection.Text = "Pe sectii:";
            trGroupByTypes.Visible = true;
            {
                filterType.Visible = false; //rd btn lst
                filterTypes.Visible = true; //chk bx lst
                //the buttons will be set below, after the switch
            }
            #endregion

            if (reportType == "genericDocs|Centralizer_Medics_Sections")
            {
                filterType.Items.Insert(0, new ListItem("Toate", "*"));
                filterType.SelectedIndex = 0;
            }
            else if (filterType.Items[0].Value == "*")
            {
                filterType.Items.RemoveAt(0);
                filterType.SelectedIndex = 0;
            }

            tdPlatiDropDown.Visible = true;
            tdPlatiCheckBox.Visible = false;

            switch (reportType)
            {
                #region documente generale
                case "genericDocs|Centralizer_Medics_Sections":
                    trSectionMedic.Visible = true;
                    trPlati.Visible = false;
                    trExtra1.Visible = true;
                    trExtra2.Visible = true;
                    filterType.Visible = true; //rd btn lst
                    //filterType.Items[0].Enabled = true;
                    //filterType.SelectedIndex = 0;
                    break;
                case "genericDocs|registerStudyPrepare.asp": //#2
                case "genericDocs|registerStudyPrepare.asp?report=invList": //#4
                    trPlati.Visible = false;
                    {
                        detailsLabel1.Visible = false; //Processed
                        detailsLabel2.Visible = true;  //ShowFullInfo
                    }
                    trInvestigationResults.Visible = true;
                    trResultValues.Visible = true;
                    filterType.Visible = true; //rd btn lst
                    //filterType.Items[0].Enabled = false;
                    //filterType.SelectedIndex = 1;
                    break;
                case "genericDocs|regPrimiri_prep.asp?report=regPrimiri": //#3
                    {
                        labelSpecifiedPayType.Visible = false;
                        bSpecifiedPayType.Visible = false;
                    }
                    trSectionMedic2.Visible = true;
                    trDetails.Visible = false;
                    trGroupBySection.Visible = true;
                    labelGroupBySection.Text = "Recomandate de:";

                    tdPlatiDropDown.Visible = false;
                    tdPlatiCheckBox.Visible = true;

                    break;
                case "genericDocs|regPrimiri_prep.asp?report=invListVarste": //#5
                    {
                        labelSpecifiedPayType.Visible = false;
                        bSpecifiedPayType.Visible = false;
                    }
                    trSectionMedic2.Visible = true;
                    trDetails.Visible = false;
                    trGroupBySection.Visible = true;
                    labelGroupBySection.Text = "Recomandate de:";

                    tdPlatiDropDown.Visible = false;
                    tdPlatiCheckBox.Visible = true;
                    break;
                #endregion

                #region CAS Laboratoare Private + CAS ambulator
                case "casLPrivat|listCASPrivateLabsPrepare.asp":
                case "casLPrivat|nominalCASPrivateLabsDetailPrepare.asp":
                case "casAmbulator|listAMBPrepare.asp":
                case "casAmbulator|nominalAMBPrepare.asp":
                case "casAmbulator|nominalAMBDetailPrepare.asp":
                    trExclusions.Visible = true;
                    trOutputFormat1.Visible = true;
                    {
                        bool bHideNameFilter = reportType.Equals("casLPrivat|listCASPrivateLabsPrepare.asp") ||
                            reportType.Equals("casAmbulator|listAMBPrepare.asp");
                        labelInternalNames.Visible = !bHideNameFilter;
                        bInternalName.Visible = !bHideNameFilter;
                    }
                    labelInternalCodes.Visible = true;
                    bInternalCode.Visible = true;
                    trGroupBySection.Visible = true;
                    if (reportType.Equals("casLPrivat|listCASPrivateLabsPrepare.asp"))
                        labelGroupBySection.Text = "Recomandate de:";
                    break;
                #endregion

                #region CAS generic
                case "casGeneric|centralizerCAS_VALPrepare.asp":
                case "casGeneric|centralizerCASPrepare.asp":
                case "casGeneric|listCASPrepare.asp":
                case "casGeneric|nominalCASPrepare.asp":
                    bool bFirstTwo = reportType.Equals("casGeneric|centralizerCAS_VALPrepare.asp") ||
                            reportType.Equals("casGeneric|centralizerCASPrepare.asp");
                    trSumming.Visible = bFirstTwo;
                    trExclusions.Visible = true;
                    trOutputFormat1.Visible = true;
                    {
                        bool bShowNameFilter = reportType.Equals("casGeneric|nominalCASPrepare.asp");
                        labelInternalNames.Visible = bShowNameFilter;
                        bInternalName.Visible = bShowNameFilter;
                    }
                    trOutputFormat2.Visible = true;
                    labelInternalCodes.Visible = !bFirstTwo;
                    bInternalCode.Visible = !bFirstTwo;
                    trGroupBySection.Visible = !bFirstTwo;
                    break;
                #endregion

                #region misc
                case "misc|generalFilePrepareSecMe.asp":
                case "misc|generalFilePrepareSecMeAn.asp":
                case "misc|generalFilePrepareSecMeAnDet.asp":
                case "misc|generalFilePrepareAnSecMe.asp":
                case "misc|generalFilePrepareAnSecMeDet.asp":
                case "misc|ClassSecMeDet.asp":
                    txtStartTime.Enabled = false;
                    //txtStartTime.ReadOnly = true;
                    txtStartTime.Text = " 0:00:00";
                    txtEndTime.Enabled = false;
                    //txtEndTime.ReadOnly = true;
                    txtEndTime.Text = "23:59:59";
                    trAnalysis.Visible = !reportType.Equals("misc|generalFilePrepareSecMe.asp");
                    trSectionMedic.Visible = true;
                    trPlati.Visible = true; //TODO: hide checkbox
                    trDetails.Visible = false;
                    trOutputFormat1.Visible = false;
                    trOutputFormat2.Visible = false;
                    trGroupByTypes.Visible = false;
                    break;
                //case "misc|ClassSecMeDet.asp":
                //    filtering.Visible = false;
                #endregion

                #region standalone
                case "genericDocs|regCereri":
                    trPlati.Visible = false;
                    trDetails.Visible = true;
                    {
                        detailsLabel1.Visible = false; //Processed
                        detailsLabel2.Visible = true;  //ShowFullInfo
                    }
                    filterType.Visible = true; //rd btn lst
                    //filterType.Items[0].Enabled = false;
                    //filterType.SelectedIndex = 1;
                    break;
                #endregion

                default:
                    filtering.Visible = false;
                    SetMessage("Selectie necunoscuta: '" + reportType + "'", true);
                    break;
            }
            bool bRadioButtonListShown = filterType.Visible;
            filterTypes.Visible = !bRadioButtonListShown; //chk bx lst
            checkAllTypes.Visible = !bRadioButtonListShown; //the 3 buttons for the chk bx lst
            customTypes.Visible = !bRadioButtonListShown;
            checkNoTypes.Visible = !bRadioButtonListShown;
        }
        #endregion
    }

    #region CheckBoxList buttons
    private void UpdateButtonsFromCheckBoxList(CheckBoxList source, Button all, Button some, Button none)
    {
        bool firstItemState = source.Items[0].Selected;
        System.Windows.Forms.CheckState listState = firstItemState ? System.Windows.Forms.CheckState.Checked : System.Windows.Forms.CheckState.Unchecked;
        foreach (ListItem item in source.Items)
            if (item.Selected != firstItemState)
            {
                listState = System.Windows.Forms.CheckState.Indeterminate;
                break;
            }
        #region update borders
        foreach (Button b in new Button[] { all, some, none })
        {
            b.BorderStyle = BorderStyle.Solid;
            b.BorderColor = Color.Black;
        }
        Button target = null;
        switch (listState)
        {
            case System.Windows.Forms.CheckState.Checked:
                //filterOutput.Text = "all";
                target = all;
                break;
            case System.Windows.Forms.CheckState.Indeterminate:
                //filterOutput.Text = "some";
                target = some;
                break;
            case System.Windows.Forms.CheckState.Unchecked:
                //filterOutput.Text = "none";
                target = none;
                break;
            default:
                SetMessage("Unknown(!!!) CheckState: " + listState.ToString(), false);
                break;
        }
        if (target != null)
        {
            target.BorderColor = Color.Blue;
            target.BorderStyle = BorderStyle.Double;
        }
        #endregion
    }
    protected void filterSection_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateButtonsFromCheckBoxList(filterSection, checkAllSections, customSections, checkNoSections);
    }
    protected void filterTypes_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateButtonsFromCheckBoxList(filterTypes, checkAllTypes, customTypes, checkNoTypes);
    }

    protected void checkButton_Click(object sender, EventArgs e)
    {
        Button source = sender as Button;
        if (source == null)
            throw new ApplicationException("Cannot determine CmdArg for the object that raised 'checkButton_Click'!");
        string cmdArg = source.CommandArgument;
        bool checking = cmdArg.StartsWith("all");
        CheckBoxList target = cmdArg.EndsWith("Sections") ? filterSection : cmdArg.EndsWith("Types") ? filterTypes : null;
        if (target == null)
            throw new ApplicationException("Cannot determine target CheckBoxList from the '" + cmdArg + "' CommandArgument!");
        foreach (ListItem item in target.Items)
            item.Selected = checking;
        filterSection_SelectedIndexChanged(null, null);
        filterTypes_SelectedIndexChanged(null, null);
    }
    #endregion

    protected void btnReport_Click(object sender, EventArgs e)
    {
        string strSpecificSection = "";
        if (trGroupBySection.Visible)
            strSpecificSection = GetSelection(filterSection);
        else
            strSpecificSection = (trSectionMedic.Visible ? strSection.SelectedItem.Text : strSection2.SelectedValue);

        bool bMustHavePayType = (trPlati.Visible ? bSpecifiedPayType : bOnlyPayType).Checked;
        string strSpecificPayType = "";

        if (trExtra1.Visible)
            strSpecificPayType = strPayType2.SelectedValue;
        else
            strSpecificPayType = ((trPlati.Visible && tdPlatiDropDown.Visible) ? strPayType.SelectedValue : GetSelection(filterTypePayment));

        bool bProcessed = detailsLabel1.Visible ? bDetails.Checked : false,
            bShowFullInfo = detailsLabel2.Visible ? bDetails.Checked : false;

        string groupByTypes = filterTypes.Visible ? GetSelection(filterTypes) : filterType.SelectedItem.Text;

		string guid = CommonSession.SetStareRapoarteLaborator(this, ddlRaportSelector.SelectedValue ?? ddlGrupRaport.SelectedValue,
            GetDate(txtStartDate, extStartDate, txtStartTime), GetDate(txtEndDate, extEndDate, txtEndTime),
            strAnalysis.SelectedValue, strSpecificSection, strMedic.SelectedValue, strMedicType.SelectedValue,
            bMustHavePayType, strSpecificPayType,
            bShowSums.Checked, bProcessed, bShowFullInfo, bTehnice.Checked,
            bNumeCodCAS.Checked, bShowRepeatCounts.Checked, bUnpaidToo.Checked, bInactiveToo.Checked,
            bInternalName.Checked, bInternalCode.Checked,
            txtInvestigatie.Text, txtRezultat.Text,
            comparerOp1.SelectedValue, comparedValue1.Text, compareType.SelectedValue, comparerOp2.SelectedValue, comparedValue2.Text,
            strSpecificSection, groupByTypes, null, strFormat.SelectedValue); //, strFormat.SelectedValue);

        switch (strFormat.SelectedValue)
        {
            case "HTML":
                Response.Redirect("Reports/CommonReports.aspx?info=" + guid, true);
                break;
            case "Word":
                break;
            case "Excel":
                break;
            default:
                break;
        }
        Response.Redirect("target.aspx?filters=" + guid, true);
    }

    private static DateTime GetDate(TextBox txtDate, CalendarExtender calendar, TextBox txtTime)
    {
        string strDate = txtDate.Text;
        if (calendar.SelectedDate.HasValue && calendar.SelectedDate.Value.ToString(calendar.Format).Equals(strDate))
            strDate = calendar.SelectedDate.Value.ToString("yyyy-MM-dd");
        return DateTime.Parse(strDate + " " + txtTime.Text);
    }

    private string GetSelection(CheckBoxList filter)
    {
        List<string> result = new List<string>();
        bool firstItemState = filter.Items[0].Selected;
        System.Windows.Forms.CheckState listState = firstItemState ? System.Windows.Forms.CheckState.Checked : System.Windows.Forms.CheckState.Unchecked;
        foreach (ListItem chk in filter.Items)
        {
            if (chk.Selected)
                if (filter.ID == "filterTypePayment" || filter.ID == "filterSection")
                    result.Add(chk.Value);
                else
                    result.Add(chk.Text);
            if (chk.Selected != firstItemState)
                listState = System.Windows.Forms.CheckState.Indeterminate;
        }
        switch (listState)
        {
            case System.Windows.Forms.CheckState.Checked:
                return "*"; //"all"?
            case System.Windows.Forms.CheckState.Indeterminate:
                return "('" + result.Join("', '") + "')";
            case System.Windows.Forms.CheckState.Unchecked:
                return string.Empty;
            default:
                SetMessage("Unknown(!!!) CheckState: " + listState.ToString(), false);
                return null;
        }
    }

    protected void btnGenerateReportIB_Click(object sender, EventArgs e)
    {
        try
        {
            switch (rdFormatSR.SelectedValue)
            {
                case "HTML":
                    Response.Redirect("Reports/CommonReports.aspx?info=" + GetGuidBuletinPrints(), true);
                    break;
                case "Word":
                    break;
                case "Excel":
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    protected void btnGenerateReportSR_Click(object sender, EventArgs e)
    {
        try
        {
            switch (rdFormatSR.SelectedValue)
            {
                case "HTML":
                    Response.Redirect("Reports/CommonReports.aspx?info=" + GetGuidResearching(), true);
                    break;
                case "Word":
                    break;
                case "Excel":
                    break;
                default:
                    break;
            }

        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    private string GetGuidBuletinPrints()
    {
        return CommonSession.SetStareRapoarteLaborator(this, "Imprimare Buletine", GetDate(txtDataStart, calDataStart, txtTimeStartIB), GetDate(txtDataEnd, calDataEnd, txtTimeEndIB), null, drpSectionIB.SelectedValue,
            drpMedicIB.SelectedValue, null, false, null, false, false, chkPtientInfIB.Checked, false, false, false, false, false, false, false, drpTypesInv.SelectedItem.Text,
            null, null, null, null, null, null, null, null, txtListaCoduri.Text, strFormat.SelectedValue);
    }

    private string GetGuidResearching()
    {
        return CommonSession.SetStareRapoarteLaborator(this, "Registru Cercetare", GetDate(txtStartDataSR, calDataStartSR, txtTimeDSSR), GetDate(txtEndDataSR, calEndDataSR, txtTimeEDSR), null, null,
            null, null, false, null, false, bDetailsSR.Checked, bTehniceSR.Checked, false, false, false, false, false, false, false, txtInvestigationSR.Text, txtResultSR.Text,
            drpSR.SelectedItem.Text, txtSR.Text, drpORNOTSR.SelectedValue, drpLESSSR.SelectedItem.Text, txtLessSR.Text, null, drpInvestigSR.SelectedItem.Text, null, strFormat.SelectedValue);
    }

}
